package net.ncraft.mc.easyframework.easygame.gamekits.board;

import net.ncraft.mc.easyframework.easygame.GamePlayer;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.Criteria;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DefaultEBoard implements EBoard {


    private final List<GamePlayer> players = new ArrayList<>();
    private final JavaPlugin plugin;
    private Scoreboard bukkitScoreboard;
    private Objective objective;
    private Render textRender;
    private String title;
    private BukkitTask bukkitTask;

    public DefaultEBoard(JavaPlugin plugin, String title) {
        this.plugin = plugin;
        this.title = title;
        init();
    }


    @Override
    public void open(GamePlayer player) {
        players.add(player);
        player.getPlayer().setScoreboard(bukkitScoreboard);
    }

    @Override
    public void close(GamePlayer player) {
        players.remove(player);
        player.getPlayer().setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());
    }

    @Override
    public void close() {
        players.forEach(this::close);
        bukkitTask.cancel();

    }

    @Override
    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public void setLines(Render render) {
        this.textRender = render;
    }

    @Override
    public void init() {
        bukkitScoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
        objective = bukkitScoreboard.registerNewObjective(UUID.randomUUID().toString(), Criteria.DUMMY, title);
        objective.setDisplaySlot(DisplaySlot.SIDEBAR);
        bukkitTask = new BukkitRunnable() {
            @Override
            public void run() {
                render();
            }
        }.runTaskTimerAsynchronously(plugin, 0, 5);
    }


    private void render() {
        if (textRender == null) return;
        List<String> handle = textRender.handle(players);
        for (int i = 0; i < handle.size(); i++) {
            objective.getScore(handle.get(i)).setScore(handle.size() - i);
        }
    }

}
